function subscribeUser(id) {
	$.getJSON("/writeonproject/create?object=usersub&userid=" + id, subUserCallback );
}

function subUserCallback(data) {
	if( data != null && data.error == "false" ) {
		
	} else {
		alert( data.reason );
	}
}

function subscribeStory() {
	var storyid = document.getElementById("storyid");
	$.getJSON("/writeonproject/create?object=storysub&storyid=" + storyid.value , subStoryCallback );
}

function subStoryCallback(data) {
	if( data != null && data.error != null && data.error == "false" ) {
		var subbox = document.getElementById("subscribe");
		subbox.innerHTML = "<span><span>Subscribed</span></span>";
	} else {
		alert( data.reason );
	}
}


function commentSubmit(event) {
	var key = event.which;
	if( key == 13 ) {
    	var textBox = document.getElementById("text_box");
    	var storyid = document.getElementById("storyid");
    	$.getJSON("/writeonproject/create?object=comment&storyid=" + storyid.value + "&comment=" + textBox.value, commentSubmitCallBack);
    	var textBox = document.getElementById("text_box");
    	textBox.value = "";
    }
}

function commentSubmitCallBack(data) {
	commentUpdate();
	if( data != null && data.error != null && data.error == "true" ) {
		alert( data.reason );
	}
}

function commentUpdate() {
	var storyid = document.getElementById("storyid");
	$.getJSON("/writeonproject/update?page=story_comment&storyid=" + storyid.value, commentCallBack);
}

function commentCallBack(data) {
	if( data != null && data.error != null && data.error == "false" ) {
		if( data.comments.length > 0 ) {
			var commentBox = document.getElementById("chat_box");
			for( var i = 0; i < data.comments.length; i++ ) {
				var comment = data.comments[i];
				if( document.getElementById( "comment" + comment.commentid ) == null) {
					commentBox.innerHTML += "<input type=\"hidden\" id=\"comment" + comment.commentid + "\">";
					commentBox.innerHTML += comment.timestamp + " [<a href=\"/writeonproject/home?page=profile&userid=" + comment.userid + "\">" + comment.userid + "</a>] says: " + comment.comment + "</br></br>";
				}
			}
		}
	} else {
		alert( data.reason );
	}
}


function upvoteStory() {
	var storyid = document.getElementById("storyid");
	$.getJSON("/writeonproject/create?object=upvote&storyid=" + storyid.value, upvoteCallBack );
}

function upvoteCallBack(data) {
	if( data != null && data.error != null && data.error == "false") {
		var upvote = document.getElementById("upvote");
		upvote.innerHTML = "<span><span>Voted!</span></span>";
	} else {
		
	}
}

function addStory() {
	var storyid = document.getElementById("storyid");
	$.getJSON("/writeonproject/update?page=get_add_lists&storyid=" + storyid.value, addStoryCallBack1 );	
}

function addStoryCallBack1(data) {
	if (data != null && data.error != null && data.error == "false" && data.storylists != null) {
		if (data.storylists.length > 0) {			
			var dialog = $("<div>Select storylists to add the current story to:<br></div>");
			dialog.attr('id', 'add_dialog');
			dialog.attr('class', 'modal_dialog');
			var mask = $("<div></div>");
			mask.attr('id', 'mask');
			mask.prependTo("#page1");
			dialog.prependTo("#page1");
			
			var listDiv = $('<div></div>');
			listDiv.attr('id', 'list_boxs');
			
			for (var i = 0; i < data.storylists.length; i++) {
				var list = data.storylists[i];
				listDiv.html( listDiv.html() + "<input type=\"checkbox\" value=\"" + list.listid + 
						"\" id=\"list" + list.listid + "\">" + list.name + "</div><br>");
			}
			
			listDiv.appendTo(dialog);
			$('<input type="button" class="dft_btn" value="OK" onClick="addStoryToLists();"></input>').appendTo(dialog);
			$('<input type="button" class="dft_btn" value="Cancel" onClick="$(\'#mask, #add_dialog\').remove();"></input>').appendTo(dialog);
			
	        var maskHeight = $(document).height();
	        var maskWidth = $(window).width();
	        
	        mask.css({'width':maskWidth,'height':maskHeight});
	        mask.fadeTo("slow",0.8);  
	        mask.show();
			
	        //Get the window height and width
	        var winH = $(window).height();
	        var winW = $(window).width();
	               
	        //Set the popup window to center
	        dialog.css('top',  winH/2-dialog.height()/2);
	        dialog.css('left', winW/2-dialog.width()/2);	     
			dialog.show();
		} else {
			alert("No available lists to add this story to!");
		}
	} else {
		alert( data.reason );
	}
}

function addStoryToLists() {
	var dialog = document.getElementById("list_boxs");
	var inputs = dialog.getElementsByTagName("input");
	var str = "";
	
	
	for (var i = 0; i < inputs.length; i++) {
		var input = inputs[i];
		if (input.checked) {
			if (str != "") {
				str += ",";
			}

			str += input.value;
		}
	}
	
	$('#mask, #add_dialog').remove();
	
	if (str == "") {
		alert("No lists selected!");
	} else {
		var storyid = document.getElementById("storyid");
		$.getJSON("/writeonproject/update?page=add_to_lists&storyid=" + storyid.value + "&listid=" + str, addStoryCallBack2 );	
	}
}

function addStoryCallBack2(data) {
	if( data != null && data.error != null && data.error == "true" ) {
		alert( data.reason );
	}
}

function contributeToStory() {
	var storyid = document.getElementById("storyid");
	var posttext = document.getElementById("post_text");
	var text = posttext.innerHTML;
	
	var tagList = "";
	var count = 0;
	while( document.getElementById( "tag" + count ) != null ) {
		var element = document.getElementById( "tag" + count );
		if( element.checked == true ) {
			if( tagList == "" ) {
				tagList += element.value;
			} else {
				tagList = tagList + "," + element.value;
			}
		}
		count++;
	}
	
	$.getJSON("/writeonproject/create?object=post&storyid=" +storyid.value + "&post=" + text +"&tags=" + tagList, contributeCallBack);
}

function contributeCallBack(data) {
	if( data != null && data.error != null && data.error == "true" ) {
		alert( data.reason );
	} else {
		document.getElementById("post_text").innerHTML = "";
	}
	
	getStoryViewUpdates();
}

function updateStoryViewInit() {
	getStoryViewUpdates();
	window.setInterval(getStoryViewUpdates, 1000);
	
	commentUpdate();
	window.setInterval(commentUpdate,1000);
	
	document.getElementById("post_text").innerHTML = "";
}

function getStoryViewUpdates() {
	var storyid = document.getElementById("storyid");
	$.getJSON("/writeonproject/update?page=story_view&storyid="+storyid.value, storyViewCallBack);
}

function storyViewCallBack(data) {
	if( data.error != null && data.error == "false") {
		var storysubbox = document.getElementById("subscribe");
		if (storysubbox != null) {
			if( data.storysub == "true" ) {
				storysubbox.innerHTML = "<span><span>Subscribed</span></span>";
			} else {
				storysubbox.innerHTML = "<span><span>Subscribe</span></span>";
			}
		}
		var upvotebox = document.getElementById("upvote");
		if (upvotebox != null) {
			if( data.upvoted == "true") {
				upvotebox.innerHTML = "<span><span>Voted</span></span>";
			} else {
				upvotebox.innerHTML = "<span><span>+1</span></span>";
			}
		}
		var tagBox = document.getElementById("post_tags");
		tagBox.innerHTML = "";
		if( data.tags.length > 0 ) {
			for( var i = 0; i < data.tags.length; i++ ) {
				var tag = data.tags[i];
				var exists = document.getElementById( "tag" + tag.tagname );
				if( tag.count > 0 ) {
					if( exists == null || exists == "undefined" || exists === undefined || exists == "null" ) {
						tagBox.innerHTML += ( "<span id=\"tag" + tag.tagname + "\"><u>" + tag.tagname + "(" + tag.count + ")</u></span>  " );
					}
				}
			}
		} else {
			tagBox.innerHTML = "None!";
		}
		var posttable = document.getElementById("post_table");
		var cur_user = data.userid;
		if( data.posts.length > 0 ) {
			for( var i = 0; i < data.posts.length; i++ ) {try{
				var post = data.posts[i];
				var exists = document.getElementById( "post" + post.postid );
				if( exists == null ) {
					var toprow = "<tr class=\"rowon\" id=\"post" + post.postid + "\"> <td class=\"posts_col1 center_col bottom_bor\"><a href=\"/writeonproject/home?page=profile&userid=" + post.userid + "\">" + post.userid + "</a><br>" + post.timestamp + "<br>";
					if (cur_user != null && cur_user != post.userid) {
						if( post.subscribed == "true" ) {
							toprow += "<a href=\"\" class=\"button shrink\" id=\"subpid" + post.postid + "\" onclick=\"subscribeUser('"+ post.userid +"'); return false;\"><span><span>Subscribed</span></span></a><br>";
						} else {
							toprow += "<a href=\"\" class=\"button shrink\" id=\"subpid" + post.postid + "\" onclick=\"subscribeUser('"+ post.userid +"'); return false;\"><span><span>Subscribe</span></span></a><br>";
						} 
					} else {
						toprow += "<br><br>";
					}
					toprow += "<br></td><td class=\"posts_col2 bottom_bor\"><p>";
					toprow += post.post;
					toprow += "</p></td></tr>";
					posttable.innerHTML += toprow;
				} else {
					var subscribed = document.getElementById( "subpid" + post.postid );
					if (subscribed != null) {
						if( post.subscribed == "true" ) {
							subscribed.innerHTML = "<span><span>Subscribed</span></span></a></td>";
						} else {
							subscribed.innerHTML = "<span><span>Subscribe</span></span></a></td>";
						} 
					}
				}}catch(e){alert(e.message);}
			}
		}
	}
}

function updatePromptInit() {
	getPromptUpdates();
	window.setInterval(getPromptUpdates, 1000 );
}

function getPromptUpdates() {
	$.getJSON("/writeonproject/update?page=browse_prompts", promptCallBack);
}

function promptCallBack(data) {
	if( data.error != null && data.error == "false" ) {
		var promptbody = document.getElementById("prompt_body");
		if( data.prompts.length > 0 ) {
			for( var i = 0; i < data.prompts.length; i++ ) {
				var prompt = data.prompts[i];
				var exists = document.getElementById('prompt'+prompt.promptid );
				if( exists == null ) {
					var trow = promptbody.insertRow( 0 );
					trow.className = "rowon";
					var first = trow.insertCell( 0 );
					var second = trow.insertCell( 1 );
					var third = trow.insertCell( 2 );
					var fourth = trow.insertCell( 3 );
					
					first.innerHTML = "<a href=\"/writeonproject/home?page=create_story&promptid=" + prompt.promptid + "\" class=\"button shrink\"><span><span>Create Story</span></span></a>";
					if( prompt.imgpath != null && prompt.imgpath != "null" ) {
						second.innerHTML = "<img src=\"" + prompt.imgpath + "\" width=\"50%\" height=\"50%\" class=\"img_preview\"/><br/>";
					}
					if( prompt.text != null && prompt.text != "null" ) {
						second.innerHTML += prompt.text;
					}
					third.innerHTML = "<a href=\"/writeonproject/home?page=profile&userid="+ prompt.userid + "\">" + prompt.userid + "</a>";
					fourth.id = "prompt" + prompt.promptid;
					fourth.innerHTML = prompt.timestamp;
				}
			}
		}
	}
}

function storyUpdateInit() {
	getStoryUpdates();
}

function getStoryUpdates() {
	$.getJSON("/writeonproject/update?page=browse_stories", storiesCallBack);
}

function storiesCallBack(data) {
	if( data != null && data.error != null && data.error == "false" ) {
		var storybody = document.getElementById('storybody');
		if( data.stories.length > 0 ) {
			for( var i = 0; i < data.stories.length; i++ ) {
				var story = data.stories[i];
				var storytime = document.getElementById( "time" + story.storyid );
				if( storytime == null ) {
					var bottomRow = storybody.insertRow ( 0 );
					var topRow = storybody.insertRow( 0 );
					
					topRow.className = "rowon story1";
					var topcell1 = topRow.insertCell( 0 );
					var topcell2 = topRow.insertCell( 1 );
					var topcell3 = topRow.insertCell( 2 );
					var topcell4 = topRow.insertCell( 3 );
					
					topcell1.innerHTML = "<a href=\"/writeonproject/home?page=story_view&storyid=" + story.storyid + "\" class=\"title\">" + story.storytitle + "</a>";
					topcell2.className = "small_date";
					topcell2.innerHTML = "<a href=\"/writeonproject/home?page=profile&userid=" + story.authorid + "\" class=\"author\">" + story.authorid + "</a><br>" + story.createdate;
					topcell3.className = "story_post";
					topcell3.id = "pcount" + story.storyid;
					topcell3.innerHTML = story.numpost;
					topcell4.className = "small_date";
					topcell4.id = "time" + story.storyid;
					topcell4.innerHTML = "<a href=\"/writeonproject/home?page=profile&userid=" + story.lastposterid + "\" class=\"author\">" + story.lastposterid + "</a><br>" + story.timestamp;
					
					bottomRow.className = "rowon";
					var bottom1 = bottomRow.insertCell( 0 );
					bottom1.className = "story_preview";
					bottom1.id = "sp" + story.storyid;
					bottom1.colSpan = "4";
					bottom1.innerHTML = story.preview;
				} else {
					var storyts = document.getElementById( "time" + story.storyid );
					storyts.innerHTML = "<a href=\"/writeonproject/home?page=profile&userid=" + story.lastposterid + "\" class=\"author\">" + story.lastposterid + "</a><br>" + story.timestamp; 
					
					var preview = document.getElementById( "sp" + story.storyid );
					preview.innerHTML = story.preview;
					
					var storyp = document.getElementById( "pcount" + story.storyid );
					storyp.innerHTML = story.numpost ;
				}
			}
		}
	}
}

function getNewsFeedInit() {
	getNewsFeedUpdates();
	window.setInterval(getNewsFeedUpdates, 1000 );
}

function getNewsFeedUpdates() {
	$.getJSON("/writeonproject/update?page=newsfeed", newsFeedCallBack );
}

function newsFeedCallBack(data) {
	if( data.error != null && data.error == "false" ) {
		var newstable = document.getElementById('newsfeedtable');
		if( data.newsfeed.length > 0 ) {
			for( var i = 0; i < data.newsfeed.length; i++ ) {
				var entry = data.newsfeed[i];
				if( document.getElementById( "newsfeed" + entry.favuserid + "story" + entry.storyid + "timestamp" + entry.timestamp ) == null ) {
					var row2 = newstable.insertRow( 0 );
					var row3 = newstable.insertRow( 0 );
					var row1 = newstable.insertRow( 0 );
					row1.className = "rowon story1";
					row2.className = "rowon story1";
					row3.className = "rowon story1";
					row1.id = "newsfeed" + entry.favuserid + "story" + entry.storyid  + "timestamp" + entry.timestamp;
					
					var cell1 = row1.insertCell(0);
					var cell2 = row2.insertCell(0);function uncheckTags(){
						
						var tagCheckboxes = document.getElementById('tagsCheckboxes');
						var boxes = tagCheckboxes.getElementsByTagName("div");
						var checkboxLength = boxes.length;
						
						for (var i = 0; i<checkboxLength; i++){
							var checkbox = document.getElementById("tag" + i);
							
							if (checkbox.checked) checkbox.checked=false;
						}
						
					}

					function browseFilterTags(){
						
						var tagCheckboxes = document.getElementById('tagsCheckboxes');
						var boxes = tagCheckboxes.getElementsByTagName("div");
						var checkboxLength = boxes.length;
						
						var tagindex = 0;
						var tagsURL = "";
						
						for (var i = 0; i<checkboxLength; i++){
							var checkbox = document.getElementById("tag" + i);
							
							if (checkbox.checked){
								tagsURL = tagsURL + "&tag" + tagindex + "=" + checkbox.value;
								tagindex++;
							}	
						}
						
						var sortBy = document.getElementById('sortBrowse');
						var index = sortBy.selectedIndex;
						var sortMethod = sortVal;

						$.getJSON("/writeonproject/update?page=browse_stories_tags" + "&tagIndex=" + tagindex + tagsURL, function(data){
							
							if( data.error != null && data.error == "false" ) {
								
								var storybody = document.getElementById('storybody');
								
								for (var i = storybody.rows.length; i > 0; i--){
									storybody.deleteRow(0);
								}
								
								if( data.stories.length == 0 ){
									var bottomRow = storybody.insertRow ( 0 );
									bottomRow.className = "rowon";
									var bottom1 = bottomRow.insertCell( 0 );
									bottom1.className = "story_preview";
									bottom1.colSpan = "4";
									bottom1.innerHTML = "Sorry, there are no matching stories for the above criteria.";
								}
								
								if( data.stories.length > 0 ) {
									if (sortMethod == "updated"){
										data.stories.sort(sortByUpdated);			
									}
									
									else if (sortMethod == "viewed"){
										data.stories.sort(function(a, b){
											return a.viewcount - b.viewcount;});
									}
									
									else if (sortMethod == "voted"){
										data.stories.sort(function(a, b){
											return a.votecount - b.votecount;});		
									}
									
									else if (sortMethod == "created"){
										data.stories.sort(sortByCreatedTime);
									}
									
									else if (sortMethod == "commented"){
										data.stories.sort(sortByCommented);			
									}
									
									for( var i = 0; i < data.stories.length; i++ ) {
										
										var story = data.stories[i];
									
											var bottomRow = storybody.insertRow ( 0 );
											var topRow = storybody.insertRow( 0 );
											
											topRow.className = "rowon story1";
											var topcell1 = topRow.insertCell( 0 );
											var topcell2 = topRow.insertCell( 1 );
											var topcell3 = topRow.insertCell( 2 );
											var topcell4 = topRow.insertCell( 3 );
											
											topcell1.innerHTML = "<a href=\"/writeonproject/home?page=story_view&storyid=" + story.storyid + "\" class=\"title\">" + story.storytitle + "</a>";
											topcell2.className = "small_date";
											topcell2.innerHTML = "<a href=\"/writeonproject/home?page=profile&userid=" + story.authorid + "\" class=\"author\">" + story.authorid + "</a><br>" + story.createdate;
											topcell3.className = "story_post";
											topcell3.innerHTML = story.numpost;
											topcell4.className = "small_date";
											topcell4.id = "time" + story.storyid;
											topcell4.innerHTML = "<a href=\"/writeonproject/home?page=profile&userid=" + story.lastposterid + "\" class=\"author\">" + story.lastposterid + "</a><br>" + story.timestamp;
											
											bottomRow.className = "rowon";
											var bottom1 = bottomRow.insertCell( 0 );
											bottom1.className = "story_preview";
											bottom1.colSpan = "4";
											bottom1.innerHTML = story.preview;
										} 
								}
								}
							});
					}
					var cell3 = row3.insertCell(0);
					cell2.className = "story_preview";
					cell1.className = "right_col";
				
					var inner3 = "<a href=\"/writeonproject/home?page=profile&userid=" + entry.favuserid + "\">" + entry.favuserid + "</a> has contributed a new post to the story <a href=\"/writeonproject/home?page=story_view&storyid="+ entry.storyid + "\">" + entry.storytitle + "</a>";
					var inner2 = entry.post.substring(0,240) + " ... ";
					var inner1 = entry.timestamp;
					
					cell3.innerHTML = inner3;
					cell2.innerHTML = inner2;
					cell1.innerHTML = inner1;
				}
			}
		}
	}
}